<?php 
function getItemFromBook($book, $key)
{
    // if (empty($book) || !key_exists($key, $book)) {
    //     throw new InvalidArgumentException("数组为空或者对应索引不存在！");
    // }
    // return $book[$key];

    if (!key_exists($key, $book)) {
        throw new IndexNotExistsException("对应索引不存在！");
    }
}

$book = [
    'title' => 'Laravel 精品课',
    'summary' => '彻底掌握 Laravel 和 Vue.js 框架， 成为合格的 PHP 全栈工程师',
    'author' => '学院君',
    'price' => 99.0,
    'website' => 'https://xueyuanjun.com/books/master-laravel',
    'created_at' => '2020',
    'is_published' => false,
];

// var_dump(getItemFromBook($book, 'desc'));
//捕获异常
// try {
//     $val = getItemFromBook([], null);
//     $val = getItemFromBook($book, 'desc');
// } catch (InvalidArgumentException $exception) {
//     echo $exception->getMessage();
//     $exit = true;
// } catch (OutOfBoundsException $exception) {
//     echo $exception->getMessage();
//     $exit = true;
// } finally {
//     $exit ? exit() : var_dump($val);
// }
// var_dump($val);

// //抛出异常
// try {
//     $val2 = getItemFromBook([], null);
//     $val2 = getItemFromBook($book, 'desc');
// } catch (InvalidArgumentException $exception) {
//     throw $exception;
// } catch (OutOfBoundsException $exception) {
//     throw $exception;

// } finally {
//     var_dump($val);
// }

//全局异常处理器
// function myExceptionHandler(Exception $exception)
// {
//     echo 'Uncaught Exception [' . get_class($exception) . ']:' . $exception->getMessage() . '<br/>';
//     echo 'Thrown in ' . $exception->getFile() . 'online ' . $exception->getLine() . '<br/>';
// }

// set_exception_handler('myExceptionHandler');

try{
    $val = getItemFromBook($book, 'desc');
} catch (InvalidArgumentException $exception) {
    throw $exception;
} catch (IndexNotExistsException $exception) {
    throw $exception;
} finally {
    if(isset($val)) {
        var_dump($val);
    } else {
        echo '异常将通过全局异常处理器处理。。。<br/>';
    }
}

class IndexNotExistsException extends LogicException
{
    
}

